<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Participant;
use App\Models\Survey;
use App\Models\VoteResult;
use App\Models\VoteTitle;
use App\Org\Developer\Helper;
use App\Org\Developer\JsonReturnInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @author  陈玉琦
 * 调查投票控制器
 */
class VoteController extends Controller
{
    private $fields = ['id', 'user_id', 'title', 'illustration', 'qrcode_image_url', 'type', 'start_time', 'end_time', 'direct_to'];

    /**
     * Display a listing of the resource.
     *
     * @return array
     */
    public function index(Request $request)
    {
        // 必须的用户 user_id
        // if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
        //     return JsonReturnInfo::ID_ERROR;
        // }

        // 调查 survey_id
        if (Helper::idInvalid($survey_id = $request->input('survey_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 必须存在且必须是用户自己的资源
            $surveyModel = Survey::select($this->fields)->where(['id' => $survey_id])->first();
            if (!(isset($surveyModel) && ($survey_id = $surveyModel->id))) {
                return JsonReturnInfo::infoFailure('要查询的调查投票不存在.');
            }
            // if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
            //     return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            // }

            $voteData = VoteTitle::select(['id', 'illustration', 'image_url'])->where(['survey_id' => $survey_id])->get();
            $surveyModel['content'] = $voteData;
            return JsonReturnInfo::infoSuccess('调查投票查询成功.', $surveyModel);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function store(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($surveyData['user_id'] = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 投票的标题
        if (empty($surveyData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 调查投票的说明
        if (empty($surveyData['illustration'] = $request->input('illustration', ''))) {
            return JsonReturnInfo::infoEmpty('illustration');
        }

        $surveyData['type'] = 'vote';

        // 生成二维码需要的前缀
        if (empty($qrcode_prefix = $request->input('qrcode_prefix', ''))) {
            return JsonReturnInfo::infoEmpty('qrcode_prefix');
        }

        // 开始时间和结束时间
        $surveyData['start_time'] = $request->input('start_time', '');
        $surveyData['end_time'] = $request->input('end_time', '');
        if (empty($surveyData['start_time']) || empty($surveyData['end_time'])) {
            return JsonReturnInfo::infoEmpty('start_time 或 end_time');
        }
        // 开始时间必须早于结束时间
        if ($surveyData['start_time'] >= $surveyData['end_time']) {
            return JsonReturnInfo::START_TIME_GET_END_TIME_ERROR;
        }
        $surveyData['start_time'] = date('Y-m-d H:i:s', intval($surveyData['start_time'] / 1000) - 8 * 3600);
        $surveyData['end_time'] = date('Y-m-d H:i:s', intval($surveyData['end_time'] / 1000) - 8 * 3600);

        // 自定义跳转链接
        $surveyData['direct_to'] = $request->input('direct_to', '');

        try {
            $survey_id = 0;

            // 一个用户可以创建重复的调查，比如关于 xxx 的投票，所以不必进行重复性校验。
            // 直接写入
            $createModel = Survey::create($surveyData);
            if (!(isset($createModel) && ($survey_id = $createModel->id))) {
                return JsonReturnInfo::infoFailure('调查投票创建失败.');
            }

            // 写入投票的数据，不管是单个还是多个，都是数组形式
            if (empty($content = $request->input('content', ''))) {
                return JsonReturnInfo::infoEmpty('content');
            }

            $content = json_decode($content, true);
            if (empty($content)) {
                return JsonReturnInfo::infoEmpty('content');
            }

            // 批量写入数据库
            $batch = [];
            foreach ($content as $key => $val) {
                $batch[] = [
                    'survey_id' => $survey_id, 
                    'illustration' => $val['illustration'], 
                    'image_url' => $val['image_url']
                ];
            }

            $result = VoteTitle::insert($batch);
            if ($result) {
                // 生成二维码
                $qrcodeImagePath = \App\Org\Developer\Helper::makeQrcodeImage($qrcode_prefix . $survey_id);

                $createModel->qrcode_image_url = $qrcodeImagePath;
                $createModel->save();
                
                return JsonReturnInfo::infoSuccess('调查投票创建成功.', ['survey_id' => $survey_id, 'qrcode_image' => $qrcodeImagePath]);
            }
            return JsonReturnInfo::infoFailure('调查创建成功，投票数据写入失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return array
     */
    public function update(Request $request, $id)
    {
        // 调查 survey_id 是否合法
        if (Helper::idInvalid($id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 投票的标题
        if (empty($surveyData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 投票的说明
        if (empty($surveyData['illustration'] = $request->input('illustration', ''))) {
            return JsonReturnInfo::infoEmpty('illustration');
        }

        $surveyData['type'] = 'vote';

        // 开始时间和结束时间
        $surveyData['start_time'] = $request->input('start_time', '');
        $surveyData['end_time'] = $request->input('end_time', '');
        if (empty($surveyData['start_time']) || empty($surveyData['end_time'])) {
            return JsonReturnInfo::infoEmpty('start_time 或 end_time');
        }
        // 开始时间必须早于结束时间
        if ($surveyData['start_time'] >= $surveyData['end_time']) {
            return JsonReturnInfo::START_TIME_GET_END_TIME_ERROR;
        }
        $surveyData['start_time'] = date('Y-m-d H:i:s', intval($surveyData['start_time'] / 1000) - 8 * 3600);
        $surveyData['end_time'] = date('Y-m-d H:i:s', intval($surveyData['end_time'] / 1000) - 8 * 3600);

        // 自定义跳转链接
        $surveyData['direct_to'] = $request->input('direct_to', '');

        try {
            // 必须存在且必须是用户自己的资源
            $surveyModel = Survey::select($this->fields)->where(['id' => $id])->first();
            if (!(isset($surveyModel) && ($survey_id = $surveyModel->id))) {
                return JsonReturnInfo::infoFailure('要修改的调查投票不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            $surveyModel->title = $surveyData['title'];
            $surveyModel->illustration = $surveyData['illustration'];
            $surveyModel->start_time = $surveyData['start_time'];
            $surveyModel->end_time = $surveyData['end_time'];
            $surveyModel->direct_to = $surveyData['direct_to'];

            $result = $surveyModel->save();
            if (!$result) {
                return JsonReturnInfo::infoFailure('调查投票修改失败.');
            }

            // 修改投票的数据，不管是单个还是多个，都是数组形式
            // 但首先要把原来的删除掉
            VoteTitle::where(['survey_id' => $id])->delete();
            // 添加新数据
            if (empty($content = $request->input('content', ''))) {
                return JsonReturnInfo::infoEmpty('content');
            }

            $content = json_decode($content, true);
            if (empty($content)) {
                return JsonReturnInfo::infoEmpty('content');
            }

            // 批量写入数据库
            $batch = [];
            foreach ($content as $key => $val) {
                $batch[] = [
                    'survey_id' => $survey_id, 
                    'illustration' => $val['illustration'], 
                    'image_url' => $val['illustration']
                ];
            }

            $result = VoteTitle::insert($batch);
            if ($result) {
                // 生成二维码
                // ……
                
                return JsonReturnInfo::infoSuccess('调查投票修改成功.', ['survey_id' => $survey_id, 'qrcode' => '']);
            }
            return JsonReturnInfo::infoFailure('调查成功，投票数据修改失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 参与者调查投票结果反馈
     * result : vote_id值 vote_titles的id
     *
     * @return array
     */
    public function reply(Request $request)
    {
        // 调查 survey_id
        // 可以根据该值查询调查类型。如果没有传递该值，则需要传递调查类型，倒不如传递该值。
        if (Helper::idInvalid($survey_id = $request->input('survey_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            // 调查记录
            $surveyModel = Survey::select($this->fields)->where(['id' => $survey_id])->first();
            if (!(isset($surveyModel) && $surveyModel->id)) {
                return JsonReturnInfo::infoFailure('该调查投票不存在.');
            }

            // 反馈结果不能为空
            if (Helper::idInvalid($result = $request->input('result', 0))) {
                return JsonReturnInfo::infoFailure('投票结果不合法.');
            }

            // 每次都是新增一条记录
            $createModel = VoteResult::create([
                'survey_id' => $survey_id,
                // 'participant_id' => $participant_id,
                'title_id' => $result
            ]);

            if (isset($createModel) && $createModel->id) {
                return JsonReturnInfo::infoSuccess('反馈结果写入成功.');
            }
            return JsonReturnInfo::infoFailure('反馈结果写入失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * 调查投票结果下载
     * 应该是要每个主题的每个选项的被选择次数
     */
    public function download(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 调查 survey_id
        if (Helper::idInvalid($survey_id = $request->input('survey_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 根据 questionnaire 的 id 查询调查的 survey_id，必须是用户自己的调查
        $surveyModel = Survey::select($this->fields)->where(['id' => $survey_id])->first();
        if (!(isset($surveyModel) && $surveyModel->id)) {
            return JsonReturnInfo::infoFailure('要下载的调查投票不存在.');
        }
        if (!Helper::isUserSelfResource($user_id, $surveyModel->user_id)) {
            return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
        }

        $sql = "SELECT s.illustration,vt.illustration as vote_title,t.counts FROM 
   (SELECT title_id,COUNT(title_id) as counts FROM thearte_vote_results WHERE title_id IN 
           (SELECT id FROM thearte_vote_titles WHERE survey_id = {$survey_id}) 
           GROUP BY title_id
   ) AS t 
LEFT JOIN thearte_surveys s ON s.id = {$survey_id}
LEFT JOIN thearte_vote_titles vt ON vt.id = t.title_id
ORDER BY vt.id ASC";

        $data = \Illuminate\Support\Facades\DB::select($sql); // 结果中每个元素都是一个 stdClass 对象。

        foreach ($data as $k => $item) {
            $data[$k] = json_decode(json_encode($item), true);
        }

        $title = [
            'illustration' => '投票说明',
            'vote_title' => '投票项目',
            'counts' => '次数'
        ];
        Helper::downloadExcel($data, $title, $surveyModel->title);// '调查投票结果-' . DateHelper::dateTimeName()
    }
}
